package cc.catface.service.app;

import cc.catface.common.output.ResultBody;
import cc.catface.dao.app.dto.LoginInDTO;
import cc.catface.dao.app.dto.LoginOutDTO;
import cc.catface.dao.app.mapper.ApUserMapperServiceImpl;
import cc.catface.dao.app.pojo.ApUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ApUserServiceImpl implements ApUserService {
    @Autowired
    private ApUserMapperServiceImpl userMapperService;

    @Override
    public ResultBody get(String phone) {
        QueryWrapper<ApUser> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        return ResultBody.success(userMapperService.getOne(wrapper));
    }

    @Override
    public ResultBody update(ApUser user) {
        boolean update = userMapperService.updateById(user);
        if (update) return ResultBody.success(get(user.getName()));
        return ResultBody.error("用户信息更新失败");
    }

    @Override
    public ResultBody add(ApUser user) {
        ResultBody resultBody = get(user.getPhone());
        if (resultBody.getData() != null) return ResultBody.success("当前手机号已存在");
        boolean add = userMapperService.save(user);
        if (add) return ResultBody.success();
        return ResultBody.error("用户添加失败");
    }

    @Override
    public ResultBody list() {
        return ResultBody.success(userMapperService.list());
    }

    @Override
    public ResultBody login(LoginInDTO in) {
        ApUser user = new ApUser();
        user.setPhone(in.getPhone());

        ResultBody resultBody = get(user.getPhone());
        if (resultBody.getData() != null) {
            LoginOutDTO out = new LoginOutDTO();
            out.setToken("has");
            return ResultBody.success(out);
        }

        boolean add = userMapperService.save(user);
        if (add) {
            LoginOutDTO out = new LoginOutDTO();
            out.setToken("new");
            return ResultBody.success(out);
        }
        return ResultBody.error("登录失败");
    }
}
